
var toSysmsgIndexUrl = rootPath + "s/sys/msg/index.cgi";
var toEditSysmsgPageUrl = rootPath + "s/sys/msg/edit.cgi";//增加或修改页面

var pageListUrl = rootPath + "s/sys/msg/pagelist";//分页显示
var saveSysmsgUrl = rootPath + "s/sys/msg/save";//保存
var removeSysmsgUrl = rootPath + "s/sys/msg/del";//删除
var detailSysmsgUrl = rootPath + "s/sys/msg/detail";//获取详情

function queryList(){
	var results;
    $("#datagrid").datagrid({
//        url : pageListUrl,
        pagination:true,//分页控件
        width : 'auto',// 面板宽度，自动列宽 
        height : 'auto',// 面板高度，自动列高 
        nowrap : false,// :当true时，显示数据在同一行上。默认true。
        checkOnSelect: true,
        rownumbers: true,
        selectOnCheck: true,
        singleSelect:false,
        autoRowHeight:true,
        fitColumns: true,
        pageNo :0,
        pageSize :10,
        queryParams : getQueryParam(),
        loadFilter : function (data) {
            if(data.opStatus == "0"){
            	$("#pageNo").val(data.data.pageNo);
            	$("#pageSize").val(data.data.pageSize);
            	results = data.data.results;
            	var rs ={
            		"rows":	data.data.results,
            		"total":data.data.totalRecord
            	};
                return rs;
                
            }
        },
        columns : [ [  {
            field:'_',
            checkbox:true,
            width:'5%'
        },{
            field : 'title',
            title : '主题',
            width : '10%',
            align : 'center',
            sortable : true
        },{
            field : 'code',
            title : '编码',
            width : '10%',
            align : 'center',
            sortable : true
        },{
            field : 'redirectUrl',
            title : '跳转地址',
            width : '10%',
            align : 'center',
            sortable : true
        }, {
            field : 'contentIsEmpty',
            title : '是否包含内容',
            width : '5%',
            align : 'center',
            formatter: function(value){
        		var result = "";
        		if(value == 0){
        			result = "是";
        		}else
        			result = "否";
        		return result;
            },
            sortable : true
        }, {
            field : 'content',
            title : '消息内容',
            width : '20%',
            align : 'center',
            sortable : true
        }, {
            field : 'payload',
            title : '描述',
            width : '15%',
            align : 'center',
            sortable : true
        }, {
            field : 'createTime',
            title : '创建时间',
            width : '10%',
            align : 'center',
            formatter:function(rs){
                if(rs){
                	var date = new Date(rs)
                    return dateToString(date);
                }
            },
            sortable : true,
        }, {
            field : 'state',
            title : '状态',
            align : 'center',
            width : '5%',
            formatter: function(value){
            	var color = "";
            	var font = "";
        		if(value == 0){
        			color = "green";
            		font = "新建";
        		}
        		if(value == 1){
        			color = "orange";
            		font = "已发送";
        		}
        		if(value == 99){
        			color = "gray";
            		font = "已删除";
        		}
        		return "<font color='"+color+"'>"+font+"</font>";
            },
            sortable : true
        }, {
            field : 'sysMessageId',
            title : '操作',
            width :'10%',
            align : 'center',
            formatter: function(value,row){
            		var result = "";
            		result += '<button class="btn btn-default btn-xs" type="button" onclick="toEditSysmsgPage(\''+value+'\')"><i class="glyphicon glyphicon-pencil"></i> 修改 </button>';
            		return result;
            },
            sortable : true
        }] ],
        onDblClickRow : function(index,row){
        }
    });
}

//获取表单参数
function getQueryParam() {
	var pageNo;
	var pageNoStr = $("#pageNo").val();
	if(pageNoStr && pageNoStr != ""){
		pageNo = parseInt(pageNoStr);
	}
	var pageSize;
	var pageSizeStr = $("#pageSize").val();
	if(pageSizeStr && pageSizeStr != ""){
		pageSizeStr = parseInt(pageSizeStr);
	}
	
	var param = {
    		pageNo : pageNo,
    		pageSize : pageSize,
    		"beginTime" : $("#beginTime").val(),
            "endTime" : $("#endTime").val(),
    		"SysMessageEntity.title" : $("#title").val(),
    		"SysMessageEntity.payload" : $("#payload").val(),
    		"SysMessageEntity.code" : $("#code").val(),
    		"SysMessageEntity.redirectUrl" : $("#redirectUrl").val(),
            "SysMessageEntity.content" : $("#content").val(),
            "SysMessageEntity.contentIsEmpty" : $("#contentIsEmpty").val(),
            "SysMessageEntity.state" : $("#state").val(),
    };
    return param;
	
}

//刷新
function refreshGrid(){
	 $("#datagrid").datagrid("reload",getQueryParam());
}

//批量删除
function removeSysmsg(sysMessageIds) {
    var idsStr = sysMessageIds.join(",");
    $.ajax({
        url : removeSysmsgUrl,
        type : 'post',
        data :{ids :idsStr},
        success : function (res) {
            if(res.opStatus == "0"){
                showTip(res.msgDesc,1000,function () {
                	refreshGrid();
                });
            }else {
                showMsg(res.msgDesc);
            }
        }
    })
};

//保存
function saveSysmsg() {
	
	var valiMsg = validate();//验证表单信息
    if(valiMsg != ""){
        showMsg(valiMsg);
        return;
    }
	
	var param = {
		
		"SysMessageEntity.sysMessageId" : $("#edit_sysMessageId").val(),
		"SysMessageEntity.redirectUrl" : $("#edit_redirectUrl").val(),
		"SysMessageEntity.content" : $("#edit_content").val(),
		"SysMessageEntity.contentIsEmpty" : $("#edit_contentIsEmpty").val(),
		"SysMessageEntity.state" : $("#edit_state").val(),
		"SysMessageEntity.title" : $("#edit_title").val(),
		"SysMessageEntity.payload" : $("#edit_payload").val(),
		"SysMessageEntity.code" : $("#edit_code").val(),
	}
	$.ajax({
        url : saveSysmsgUrl,
        type : 'post',
        data :param,
        success :function (res) {
        	if(res.opStatus == "0"){
        	 showTip(res.msgDesc,1000,function () {
                 $("#editModal").modal("hide");

                 refreshGrid();
             });
        	}else {
              showMsg(res.msgDesc);
        	}
        }
    });
}

//转到编辑页面（修改或增加）
function toEditSysmsgPage(sysMessageId){
	if(sysMessageId && sysMessageId != ""){
		//修改
		$("#edit-modal").load(toEditSysmsgPageUrl + "?sysMessageId=" + sysMessageId,{_: Math.random()},function () {
			 $.ajax({
		            url : detailSysmsgUrl,
		            type : 'post',
		            data :{'id' : sysMessageId},
		            success :function (res) {
			               if( res.opStatus == "0"){
			            	   
			            	   $("#edit_title").val(res.data.title);
			            	   $("#edit_code").val(res.data.code);
			            	   $("#edit_payload").val(res.data.payload);
			            	   $("#edit_redirectUrl").val(res.data.redirectUrl);
			            	   $("#edit_content").val(res.data.content);
			            	   
			            	   $("#edit_contentIsEmpty").val(res.data.contentIsEmpty);
			            	   $("#edit_state").val(res.data.state);
			            	   
			            	   //系统消息编码不能修改
			            	   $("#edit_code").attr("readonly","readonly");
			               }else {
			            	   showMsg(res.msgDesc);
			               }
			               $('#editModalLabel').html("修改");
			               $('#editModal').modal('show');
			               
		                }
		        });
		    });
	}else {//添加
		$("#edit-modal").load(toEditSysmsgPageUrl,{_: Math.random()},function () {
			 $('#editModal').modal('show');
		});
	}
}

//验证表单信息
function validate(){
	var msg = "";
	//必填项的自定义属性 require 为 true,获取这些 input ,如果所填内容为空，则显示提示信息（data-message属性）
	var inputs = $("#msgEdit input[require='true']");
	var err = checkEmpty(inputs);
	debugger;
	$(err).each(function(){
		msg += $(this).attr("data-message")+"</br>";
	});
	//若选择为有内容，则需要填写消息内容
	var isEmpty = $("input[id='edit_contentIsEmpty']:checked").val();
	if(isEmpty == null || isEmpty == ""){
		msg += "请选择是否包含内容" + "</br>";
	}else if(isEmpty == "1"){
		var content = $("#edit_content").val();
		if(content == null || content == ""){
			msg += "请输入内容" + "</br>";
		}
	}
	var stat = $("input[id='edit_state']:checked").val();
	if(stat == null || stat == ""){
		msg += "请选择状态" + "</br>";
	}
	return msg;
}

$(document).ready(function () {
	queryList();// 加载分页数据
	
	$("#search_button").on("click",function () {
		refreshGrid();
    });
	
	$("#remove_button").on("click",function () {
    	var rows = $("#datagrid").datagrid("getChecked");
        if(rows.length > 0){
            showConfirm("是否确认删除？",function () {
                var sysMessageIds = [];
                for(var i in rows ){
                	sysMessageIds.push(rows[i].sysMessageId);
                }
                removeSysmsg(sysMessageIds);
            });
        }else {
            showMsg("请选择要删除的消息！");
        }
		
	});
	
	$("#add_button").on("click",function(){
		toEditSysmsgPage("");
	});

	var rows = $("#datagrid").datagrid("getPager");
	 $("#datagrid").datagrid({
		 url : pageListUrl,
		 onBeforeLoad:function(param){
            param.pageSize = param.rows;
            param.pageNo = param.page;
            param.rows = null;
            param.page = null;
        }
    }); 
	
});

